from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from django.contrib.auth.models import User

from .models import Funkspruch
from crew.models import Wachtag
from crew.views import lastWachtagisOver


def index(request, addContext = {}, statusCode = 200):
    users = list()
    if lastWachtagisOver():
        usersUnformatted = User.objects.all()
    else:
        latestWachtag = Wachtag.objects.latest()
        usersUnformatted = latestWachtag.users.all()
    for user in usersUnformatted:
        users.append(user.username)
    context = {
        "users": users,
    }
    # merges two dicts, needs 3.5 or greater. Double entries gets replaced by 2nd dict's.
    context = {**context, **addContext}
    return HttpResponse(render(request, "funk/index.html", context), status=statusCode)


def history(request): # turn into listview TODO
    today = timezone.localdate()
    todaysFunks = filterForDate(today) # holt heutige Funksprüche
    context = {
        "todays_funks": todaysFunks,
    }
    return HttpResponse(render(request, "funk/history.html", context))

class DetailView(generic.DetailView):
	model = Funkspruch
	template_name = 'funk/detail.html'
    

def add(request): # belongs to index.html
    if not request.user.is_authenticated: # nicht eingeloggte werden weggeleitet
        return render(request, 'index/login_error.html')
    for x in ["to","message"]: # Felder die ausgefüllt werden müssen. "from" nicht, da in dem Fall einfach der aktuell eingeloggte Nutzer genommen wird.
        if not request.POST[x]:
            return index(request, {"error_message":"Nachricht und Empfänger müssen ausgefüllt werden."}, 400)
        #else:
            #print(request.POST[x])
    try:
        newFunk = Funkspruch()
        if not request.POST["from"]:
            if request.user.is_authenticated: # always true -> read only attribute
                newFunk.fromOp = request.user.username
            else:
                 raise Exception("Not logged in.")
        else:
            newFunk.fromOp = request.POST["from"]
        newFunk.toOp = request.POST["to"]
        newFunk.message = request.POST["message"]
        newFunk.save()
    except Exception as e:
        # newFunk muss nicht gelöscht werden, da er erst am Ende gespeichert wird, bei Fehlern wird also vorher abgebrochen
        return index(request, {"error_message":"Interner Fehler.\n" + str(e)}, 400)
    return HttpResponseRedirect(reverse('funk:index'))


# helper function
def filterForDate(date):
    return Funkspruch.objects.filter(date__year=date.year,
                          date__month=date.month,
                          date__day=date.day)
